package com.ht.util;

import io.jsonwebtoken.lang.Assert;

import java.security.MessageDigest;

/**
 * @ClassName EncryptionUtil
 * @Description TODO（EncryptionUtil加密类）
 * @Author hejialun
 * @Date 2022/12/8 12:03
 * @Version 1.0
 */
public class EncryptionUtil {
    // md5加密
    public static String md5(String inputText) {

        return encrypt(inputText,"md5");
    }

    // sha加密
    public static String sha(String inputText) {

        return encrypt(inputText,"sha-1");
    }
    /**
     * md5或sha-1加密
     *
     * @param inputText
     *              要加密的内容
     * @param algorithmName
     *              加密算法名称:md5或者sha-1,不区分大小写
     * @return
     */
    public static String encrypt(String inputText, String algorithmName){

        Assert.hasLength(inputText,"请输入要加密的内容!!!");
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithmName);
            messageDigest.update(inputText.getBytes("UTF8"));
            byte[] s = messageDigest.digest();
            return hex(s);
        } catch (Exception e) {
            System.out.println("对不起，没有这样的算法");
        }
        return "";
    }

    private static String hex(byte[] s) {

        StringBuffer sb = new StringBuffer();
        for (int i = 0 ;i < s.length; i++) {
            sb.append(Integer.toHexString((s[i] & 0xFF) | 0x100).substring(1,3));
        }
        return sb.toString();
    }

}
